const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;
const compiler = require('vue-template-compiler');
const { parse } = require('@vue/compiler-sfc');

const code1 = `
<template>
  <el-form
    :model="oParams"
    :rules="rules"
    ref="em_form"
    label-width="252px"
    content-width="480px"
  >
    <!-- 图片附件 & 抓图时间间隔 -->
    <div v-if="oCapbilities.bSptSnapShoot">
      <el-form-item :label="$t('attachedImage')">
        <el-switch v-model="oParams.bEnablePic"></el-switch>
      </el-form-item>
      <el-form-item :label="$t('captureInterval')" v-show="oParams.bEnablePic">
        <el-select v-model="oParams.szPicInterval" class="el-input--width">
          <el-option v-for="(item) in oCapbilities.aEmailOptions" :key="item" :value="item" :label="item + $t('seconds')"></el-option>
        </el-select>
      </el-form-item>
      <!-- 后智能周界抓图 -->
      <el-form-item v-if="oCapbilities.bSupportInteliCaptureEnabled && oParams.bEnablePic" :label="$t('inteliCaptures')">
        <el-switch v-model="oParams.inteliCaptureEnabled"></el-switch>
      </el-form-item>
    </div>
  </el-form>
</template>

<script>
import WebSDK from '@/Common/service/request/websdk';
import { isEmail, nodeValue, checkAddressingType, parseXmlFromStr } from '@/Common/utils/utils.js';
import Response from '@/Common/service/response.js';
import Device, { testNet } from '@/Common/service/device.js';
import { validateNull, validateNoMoreLength, validatePassNameUp, validateRange } from '@/Common/utils/pc/validate.js';
import Common from '@/Common/service/common.js';
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    let that = this;
    let validatePass = (rule, value, callback) => {
      that.$refs['em_form'].validateField('cofirmPassword');
      callback();
    };
    let validatePass2 = (rule, value, callback) => {
      if (value !== that.oParams.oPassword) {
        callback(new Error(that.$t('passNotMatch')));
      } else {
        callback();
      }
    };
    let validateSecSmtpPass = (rule, value, callback) => {
      that.$refs['em_form'].validateField('SecSmtpcofirmPassword');
      callback();
    };
    let validateSecSmtpPass2 = (rule, value, callback) => {
      if (value !== that.oParams.oSecSmtpPassword) {
        callback(new Error(that.$t('passNotMatch')));
      } else {
        callback();
      }
    };
    let validtor = (rule, value, callback)=>{
      if (value !== "" && !isEmail(value)) {
      } else {
        callback();
      }
    };
    let receiverAddrValidtor = (rule, value, callback)=>{
      if (value !== "" && !isEmail(value)) {
      } else {
        callback();
      }
    };
    return {
      oCapbilities: {
        bSupportModify: Device.m_oDeviceCapa.iCmEmailType === 3,
        bSptSnapShoot: true,
        aEmailOptions: [],
        bSupportSSLTLS: true,
        bSupportEmailEncryption: false,
        bSupportSecondarySMTP: false, //支持备用smtp
        aEncryptionType: [], // 邮件加密类型
        bSupportSmartTLS: false, // 是否支持STARTTLS
        iReceiverMaxNum: 3 // 可设置的收件人的最大个数
      },
      oParams: {
        szSenderAddress: "",
        szSmtpServer: "",
        szSmtpPort: "",
        bEnableSSL: false,
        bEnablePic: false,
        szPicInterval: "",
        bAuthentication: "",
        szUserName: "",
        oPassword: Common.m_szDefaultPwd,
        cofirmPassword: Common.m_szDefaultPwd,
        szPasswordDefault: Common.m_szDefaultPwd,
        inteliCaptureEnabled: false,
        benabledSecSmtp: false,
        bSecSmtpAuthentication: false,
        szSecSmtpServer: "",
        szSecSmtpPort: "",
        bSecSmtpEnableSSL: false,
        szEncryptionType: "",
        szEncryptionTypeCache: "", //缓存加密类型，选择不加密模式确认时需要用到
        bEnableSTARTTLS: false,
        szSecSmtpUserName: "",
        oSecSmtpPassword: Common.m_szDefaultPwd,
        SecSmtpcofirmPassword: Common.m_szDefaultPwd,
        szSecSmtpPortDef: 25,
        bShowReceiverDlg: false, //收件人编辑弹框
        szReceiverEditMode: "add" //收件人编辑模式：添加或修改
      },
      receiverList: [],
      selectedReceiver: [],
      oReceiverDlgParams: { //收件人弹框参数
        iId: 1,
        szReceiverName: "",
        szReceiverAddress: ""
      },
      isSupportEmailTest: Device.m_oDeviceCapa.isSupportEmailTest,
      emailCmd: Device.m_oDeviceCapa.bSupportEmailEncrypt ? "emailEncrypt" : "email",
      emailTestCmd: Device.m_oDeviceCapa.bSupportEmailEncrypt ? "testEmailEncrypt" : "testEmail",
      disableTestEmail: true // 是否禁用邮箱测试
    }
  },
  methods: {
    // 主SMTP端口默认值
    enableSSLchange(e) {
      this.oParams.szSmtpPort = e ? "587" : "25";
    },
    // 备用SMTP端口默认值
    enableSecSSLchange(e) {
      this.oParams.szSecSmtpPort = e ? "587" : "25";
    },
    getEmailCap () {
      let that = this;
      return new Promise(resolve=> {
        WebSDK.WSDK_GetDeviceConfig("emailCap", {
          success: (xmlDoc) => {
            that.oCapbilities.bSupportInteliCaptureEnabled = false;
            this.name = 999;
          },
        });
      });
    },

    async getEmailInfo () {
      let that = this;
      await that.getEmailCap();
      WebSDK.WSDK_GetDeviceConfig(this.emailCmd, {
        success: (xmlDoc) => {
          if (that.oCapbilities.bSptSnapShoot) {
            that.oParams.bEnablePic = nodeValue(xmlDoc, "enabled", "b");
            that.oParams.szPicInterval = nodeValue(xmlDoc, "interval");
          }
          
        },
        error: (error, xhr) => {
          xhr && Response.getState(xhr);
        }
      });
    },
    addReceiver() {
      let oParams = this.oParams;
      oParams.bShowReceiverDlg = true;
      oParams.szReceiverEditMode = "add";
      this.oReceiverDlgParams.iId = this.receiverList.length + 1;
      this.oReceiverDlgParams.szReceiverName = "";
      this.oReceiverDlgParams.szReceiverAddress = "";
      setTimeout(() => {//重新触发一下校验
        this.$refs['receiver_form'].resetValidates();
      });
    },
    // 删除选中的收件人
    deleteReceiver() {
      this.selectedReceiver.forEach((val1) => {
        this.receiverList.forEach((val2, index) => {
          if (val2.id === val1.id) {
            this.receiverList.splice(index, 1);
          }
        });
      });
      this.receiverList.forEach((val, index) => {
        val.id = index + 1;
      });
    },
    // 修改收件人
    modifyReceiver(oReceiver) {
      this.oParams.bShowReceiverDlg = true;
      this.oParams.szReceiverEditMode = "modify";
      this.oReceiverDlgParams.iId = oReceiver.id;
      this.oReceiverDlgParams.szReceiverName = oReceiver.name;
      this.oReceiverDlgParams.szReceiverAddress = oReceiver.emailAddress;
    },
    cancelReceiverDlg() {
      this.oParams.bShowReceiverDlg = false;
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

`;

const code = `
import WebSDK from '@/Common/service/request/websdk';
import { isEmail, nodeValue, checkAddressingType, parseXmlFromStr } from '@/Common/utils/utils.js';
import Response from '@/Common/service/response.js';
import Device, { testNet } from '@/Common/service/device.js';
import { validateNull, validateNoMoreLength, validatePassNameUp, validateRange } from '@/Common/utils/pc/validate.js';
import Common from '@/Common/service/common.js';
export default {
  methods: {
    // 主SMTP端口默认值
    enableSSLchange(e) {
      this.oParams.szSmtpPort = e ? "587" : "25";
    },
    // 备用SMTP端口默认值
    enableSecSSLchange(e) {
      this.oParams.szSecSmtpPort = e ? "587" : "25";
    },
    getEmailCap () {
      let that = this;
      return new Promise(resolve=> {
        WebSDK.WSDK_GetDeviceConfig("emailCap", {
          success: (xmlDoc) => {
            that.oCapbilities.bSupportInteliCaptureEnabled = false;
            this.name = 999;
          },
        });
      });
    },

    async getEmailInfo () {
      let that = this;
      await that.getEmailCap();
      WebSDK.WSDK_GetDeviceConfig(this.emailCmd, {
        success: (xmlDoc) => {
          if (that.oCapbilities.bSptSnapShoot) {
            that.oParams.bEnablePic = nodeValue(xmlDoc, "enabled", "b");
            that.oParams.szPicInterval = nodeValue(xmlDoc, "interval");
          }
          
        },
        error: (error, xhr) => {
          xhr && Response.getState(xhr);
        }
      });
    },
    addReceiver() {
      let oParams = this.oParams;
      oParams.bShowReceiverDlg = true;
      oParams.szReceiverEditMode = "add";
      this.oReceiverDlgParams.iId = this.receiverList.length + 1;
      this.oReceiverDlgParams.szReceiverName = "";
      this.oReceiverDlgParams.szReceiverAddress = "";
      setTimeout(() => {//重新触发一下校验
        this.$refs['receiver_form'].resetValidates();
      });
    },
    // 删除选中的收件人
    deleteReceiver() {
      this.selectedReceiver.forEach((val1) => {
        this.receiverList.forEach((val2, index) => {
          if (val2.id === val1.id) {
            this.receiverList.splice(index, 1);
          }
        });
      });
      this.receiverList.forEach((val, index) => {
        val.id = index + 1;
      });
    },
    // 修改收件人
    modifyReceiver(oReceiver) {
      this.oParams.bShowReceiverDlg = true;
      this.oParams.szReceiverEditMode = "modify";
      this.oReceiverDlgParams.iId = oReceiver.id;
      this.oReceiverDlgParams.szReceiverName = oReceiver.name;
      this.oReceiverDlgParams.szReceiverAddress = oReceiver.emailAddress;
    },
    cancelReceiverDlg() {
      this.oParams.bShowReceiverDlg = false;
    }
  }
};
`;

// 解析代码生成AST
// const ast = parser.parse(code1, {
//   sourceType: 'module',
// });

const { descriptor } = parse(code1);
const scriptContent = descriptor.script.content;

// 解析 JavaScript 代码为 AST
const ast = parser.parse(scriptContent, {
  sourceType: 'module',
  plugins: [
    'objectRestSpread',
    'classProperties',
    'asyncGenerators',
    'optionalChaining',
    'decorators-legacy'
  ]
});

// 存储所有符合条件的赋值语句
const targetAssignments = [];

// 遍历AST
traverse(ast, {
  CallExpression(path) {
    const { callee, arguments: args } = path.node;
    
    // 检查第二个参数是否为对象且包含success/sucess回调
    if (args.length >= 2 && args[1].type === 'ObjectExpression') {
      const optionsObj = args[1];
      
      // 查找success/sucess回调
      optionsObj.properties.forEach(prop => {
        // 防御性检查：确保属性有值且类型为函数
        if (
          prop.value &&
          (prop.key.name === 'success' || prop.key.name === 'sucess') &&
          (prop.value.type === 'FunctionExpression' || 
           prop.value.type === 'ArrowFunctionExpression')
        ) {
          const callbackPath = path.get('arguments')[1].get('properties').find(
            p => p.node === prop
          ).get('value');
          
          // 处理回调函数体
          const bodyPath = callbackPath.get('body');
          
          if (bodyPath.isBlockStatement()) {
            // 处理有花括号的函数体
            bodyPath.traverse({
              AssignmentExpression(assignPath) {
                checkThisNameAssignment(assignPath, callee, prop);
              }
            });
          } else if (bodyPath.isAssignmentExpression()) {
            // 处理直接返回赋值表达式的箭头函数
            checkThisNameAssignment(bodyPath, callee, prop);
          }
        }
      });
    }
  }
});

// 检查赋值语句是否为 this.name = ...
function checkThisNameAssignment(assignPath, callee, callbackProp) {
  const assignNode = assignPath.node;
  
  if (
    // assignNode.left.type === 'MemberExpression' &&
    // assignNode.left.object.type === 'ThisExpression' &&
    // assignNode.left.property.name === 'name'

    assignNode.left.type === 'MemberExpression' && // bEnablePic 属性
    assignNode.left.object.type === 'MemberExpression' && // oParams 对象
    assignNode.left.object.object.type === 'Identifier' && // that 变量
    assignNode.left.object.object.name === 'that' &&
    assignNode.left.object.property.type === 'Identifier' &&
    assignNode.left.object.property.name === 'oParams' &&
    assignNode.left.property.type === 'Identifier' &&
    assignNode.left.property.name === 'bEnablePic'

  ) {
    targetAssignments.push({
      functionName: callee.name || 'anonymous',
      line: assignNode.loc.start.line,
      column: assignNode.loc.start.column,
      code: generate(assignNode).code,
      isMisspelled: callbackProp.key.name === 'sucess'
    });
  }
}

// 打印结果
console.log('找到的this.name赋值语句:');
targetAssignments.forEach(({ functionName, line, column, code, isMisspelled }, index) => {
  console.log(`\n${index + 1}. 函数: ${functionName}`);
  console.log(`   位置: 第${line}行，第${column}列`);
  console.log(`   代码: ${code}`);
  if (isMisspelled) console.log(`   ⚠️ 警告: 使用了错误的回调名称 "${callbackProp.key.name}"`);
});